package com.mini.init;

import com.mini.client.cache.CacheMnsClient;
import com.mini.common.config.SpringCacheConfig;
import com.mini.common.config.WebAppConfigurer;
import com.mini.mysql.model.BusinessTeacherInfo;
import com.mini.mysql.service.BusinessTeacherInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author anjl
 * @date 2020-08-27
 **/
@Slf4j
@Component
public class RobotInitRunnerImpl implements ApplicationRunner {

    @Autowired
    private BusinessTeacherInfoService businessTeacherInfoService;
    @Autowired
    private CacheMnsClient cacheMnsClient;

    @Override
    public void run(ApplicationArguments args) {
        //初始化刷新所有运营专员信息
        refreshAllTeachersAndGroups();
    }

    public void refreshAllTeachersAndGroups() {
        commonTaskExecutor.execute(() -> {
            log.info("开始刷新teachers信息");
            List<BusinessTeacherInfo> all = businessTeacherInfoService.findAll();
            Cache teacherCache = cacheManager.getCache(SpringCacheConfig.TEACHER);
            all.forEach(teacher -> teacherCache.put(Arrays.asList(teacher.getTeacherId()), teacher));
            log.info("刷新teachers完成， 共刷新条数 {}", all.size());
            Set<Long> allGroupIds = all.stream().map(BusinessTeacherInfo::getGroupId).collect(Collectors.toSet());
            allGroupIds.forEach(groupId -> cacheMnsClient.getDeptFullName(WebAppConfigurer.getSign(), groupId));
            log.info("刷新groups完成， 共刷新条数 {}", allGroupIds.size());
        });
    }

    @Resource(name = "commonTaskExecutor")
    private AsyncTaskExecutor commonTaskExecutor;
    @Autowired
    private CacheManager cacheManager;

}
